//
//  YZYSuspendManager.m
//  ZCLightSDK
//
//  Created by 赵隆杰 on 2024/5/24.
//  Copyright © 2024 Vanney. All rights reserved.
//

#import "YZYSuspendManager.h"
#import "WebSocketUtility.h"
#import "YZYSDKManagerHeader.h"
#import "YZYH5SocialView.h"
#import "ZCFunDataFormat.h"
#import "YZYRoleInfo.h"
#import "YZYSDKManager.h"

@interface YZYSuspendManager ()<YZYH5SocialViewDelegte>

//以下h5如果同时出现需要排队等待，当前只允许一个显示
@property (nonatomic, strong) YZYH5SocialView *h5SocialView;

@property (nonatomic, strong) NSMutableArray *receiveMsgArray;

@property (nonatomic, strong) YZYRoleInfo *roleInfo;

@end
 
@implementation YZYSuspendManager
 
/**
 单例模式

 @return YZYSuspendManager
 */
+ (instancetype)sharedInstance {
    static YZYSuspendManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[YZYSuspendManager alloc] init];
    });
    return shareManager;
}

- (void)props_roleUpdateWithRoleModel:(YZYRoleInfo *)roleModel {
    self.roleInfo = roleModel;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WebSocketDidOpen) name:kWebSocketDidOpenNote object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(WebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];
    
    //社群长链接
    [WebSocketUtility instance].userInfo = roleModel;
    [[WebSocketUtility instance] WebSocketOpenWithURLString:YZY_WebSocketUrl];
    
}

- (void)WebSocketDidOpen {
    NSLog(@"开启成功");
//    [self sendWebSocketDataWithCommandId:@"10008"];//新消息 返回10010有新消息 10009无消息
//    [self sendWebSocketDataWithCommandId:@"10012"];//扶持号 会返回给我10000
//    [self sendWebSocketDataWithCommandId:@"10013"];//符合条件 会返回给我20005强制打开聊天
}

- (void)WebSocketDidReceiveMsg:(NSNotification *)note {
//    NSLog(@"收到服务端发送过来的消息");
    NSString * message = note.object;
    
    NSDictionary *receiveMsg = [ZCFunDataFormat dictionaryWithJsonString:message];
    
    NSLog(@"receiveMsg - %@", receiveMsg);
    
    NSString *commandId = [NSString stringWithFormat:@"%@",receiveMsg[@"commandId"]];
    NSString *code = [NSString stringWithFormat:@"%@",receiveMsg[@"code"]];
//    NSString *msg = [NSString stringWithFormat:@"%@",receiveMsg[@"msg"]];
    NSDictionary *data = (NSDictionary *)receiveMsg[@"data"];
    if ([code isEqualToString:@"200"]) {
        if ([commandId isEqualToString:@"9526"]) {
            //打开h5
            if ([ZCFunDataFormat isBlankDictionary:data]) {
                return;
            }
            NSString *url = [NSString stringWithFormat:@"%@",data[@"url"]];
            if ([ZCFunDataFormat isBlankString:url]) {
                return;
            }
            [self.receiveMsgArray addObject:receiveMsg];
            //先判断当前是否有h5展示，有则排队等待
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary *receiveMsg = self.receiveMsgArray.firstObject;
                [self showYZYH5SocialViewWithReceiveMsg:receiveMsg];
            });
        }
    }
    
}

- (void)sendWebSocketDataWithCommandId:(NSString *)commandId {
    [self sendWebSocketDataWithCommandId:commandId messageId:nil];
}

- (void)sendWebSocketDataWithCommandId:(NSString *)commandId messageId:(NSString *)messageId {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"superUserId"] = self.roleInfo.super_user_id;
    params[@"uid"] = self.roleInfo.super_role_id;
    params[@"gameId"] = [ZCFunDataFormat GetQPGameID];
    params[@"serviceId"] = self.roleInfo.service_id;
    params[@"commandId"] = commandId; //  10001获取供工单红点推送请求, 10002删除角色工单红点消息请求
    if (messageId != nil) {
        params[@"messageId"] = messageId; //  目前只有10004需要加messageId
    }
    NSError *paramsError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&paramsError];
    NSString *paramsStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [[WebSocketUtility instance] sendData:paramsStr];
}

//关闭长链接
- (void)WebSocketClose {
    self.roleInfo = nil;
    [[WebSocketUtility instance] WebSocketClose];
}

#pragma mark - YZYH5SocialView
- (void)showYZYH5SocialViewWithReceiveMsg:(NSDictionary *)receiveMsg {
    NSLog(@"yzysdk - showYZYH5SocialViewWithReceiveMsg receiveMsg %@", receiveMsg);
    if (_h5SocialView) {
        //当前已经存在弹框，需要排队
        NSLog(@"当前已经存在弹框，需要排队");
        return;
    }
    YZYH5SocialView *h5SocialView = [[YZYH5SocialView alloc] initWithRoleInfo:self.roleInfo receiveMsg:receiveMsg];
    h5SocialView.delegate = self;
    [h5SocialView showH5SocialView];
    self.h5SocialView = h5SocialView;
    //显示后需要在存储池中移除掉
    [self.receiveMsgArray removeObjectAtIndex:0];
}

#pragma mark - YZYH5SocialViewDelegte
- (void)closeH5SocialView {
    NSLog(@"yzysdk - closeH5SocialView");
    [self closeH5SocialView0:YES];
}
- (void)closeH5SocialView0:(BOOL)nextShow {
    NSLog(@"yzysdk - closeH5SocialView0 nextShow %d, _h5SocialView %@, self.receiveMsgArray %@", nextShow, _h5SocialView, self.receiveMsgArray);
    if (_h5SocialView) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.h5SocialView removeFromSuperview];
            self.h5SocialView = nil;
        });
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //后面还有排队的，依次显示
        if (nextShow && self.receiveMsgArray.count) {
            NSDictionary *receiveMsg = self.receiveMsgArray.firstObject;
            [self showYZYH5SocialViewWithReceiveMsg:receiveMsg];
        }
    });
}
- (void)H5SocialView_switch_logout:(NSInteger)tag {
    NSLog(@"yzysdk - H5SocialView_switch_logout tag %ld", (long)tag);
    [self closeH5SocialView0:NO];
    [[YZYSDKManager shareManager] yzy_logoutPlatform];
}

- (NSMutableArray *)receiveMsgArray {
    if (!_receiveMsgArray) {
        _receiveMsgArray = [[NSMutableArray alloc] init];
    }
    return _receiveMsgArray;
}
 
@end
